<!--
 * @Description: 二维表
-->
<template>
	<div class="twoContainer">
		<div style="width: 100%; height: 90%" ref="container"></div>
		<div class="pagi">
			<!-- <Button v-if="!canScroll" primary_btn_bg :disabled="!pageState.pre" @click="handlePagi('pre')"
				>上一页</Button
			>
			<Button v-if="!canScroll" primary_btn_bg :disabled="!pageState.next" @click="handlePagi('next')"
				>下一页</Button
			> -->
			<Pagination className="fixed-page" v-model:current="current" @change="handlePagi" :total="total"></Pagination>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import { PivotSheet, S2Event, FONT_FAMILY, EXTRA_FIELD } from "@antv/s2";
import { debounce } from "lodash";
import Button from "@/components/AntdDesign/Button/Button.vue";
import Pagination from "@/components/AntdDesign/Pagination/Pagination.vue";
const container = ref(null);
import { useVModelHook } from "@/hooks/useVModelHook.js";
const props = defineProps({
	modelValue: {
		type: Object,
		default: () => {},
	},
	styles: {
		type: [Object, Array],
		default: () => new Array(),
	},
});
const emit = defineEmits(["update:modelValue", "changePagi", "change-linkage"]);
const newValue = useVModelHook(props, emit);
const current = ref(1);
const total = ref(100)
const pageState = reactive({
	next: true,
	pre: true,
});
const handlePagi = (c, s) => {
	console.log('c, s', c, s);
	emit("changePagi", c, s);
};
let s2 = null;
const cellColor = ref({
	colCell: "#ffffff",
	rowCell: "#ffffff",
});
let aggregationId = ''
const s2DataConfig = {
	valueInCols: true
};
const s2Options = {
	hierarchyType: "tree",
	showDefaultHeaderActionIcon: true,
	tooltip: {
		enable: true,
		operation: {
			// 开启组内排序
			sort: true,
		},
	},
	interaction: {
		selectedCellsSpotlight: true,
		hoverHighlight: false,
		copy: { enable: true },
	},
	// 配置小计总计显示
	totals: {
		row: {
			showGrandTotals: true,
			showSubTotals: true,
			reverseGrandTotalsLayout: false,
			reverseSubTotalsLayout: false,
			// subTotalsDimensions: ["province"],
			grandTotalsLabel: "小计",
			subTotalsLabel: "小计",
		},
		col: {
			showGrandTotals: true,
			showSubTotals: true,
			reverseGrandTotalsLayout: true,
			reverseSubTotalsLayout: false,
			subTotalsDimensions: ["province"],
			grandTotalsLabel: "总计",
			subTotalsLabel: "总计",
		},
	},
	style: {
		colCell: {
			height: 50,
		},
		dataCell: {
			width: 100,
			height: 50,
		},
	}
};
var time = null 
var timer1 = null // 滚动到底部的计时器
var timer2 = null // 滚动到顶部的计时器  
var upNum = 0
var downNum = 0
const canScroll = ref(true)
const initTwoDimenTable = async () => {
	const BORDER_COLOR = "#4B4B50";
	const HEADER_BACK_COLOR = "#24293f";
	const s2Theme = {
		background: {
			color: "#26252C", // 画布的背景颜色
		},
		empty: {
			icon: {
				fill: "#fff",
				width: 64,
				height: 41,
				margin: {
					top: 0,
					right: 0,
					bottom: 24,
					left: 0,
				},
			},
			description: {
				fontFamily: FONT_FAMILY,
				fontSize: 12,
				fontWeight: "normal",
				fill: "#fff",
				opacity: 1,
			},
		},
		cornerCell: {
			// 角头
			cell: {
				horizontalBorderColor: "#37353d",
				verticalBorderColor: "#37353d",
				backgroundColor: HEADER_BACK_COLOR,
			},
			text: {
				fill: "#ffffff",
				fontSize: 18,
				textAlign: "center",
			},
			bolderText: {
				fill: "#ffffff",
				fontSize: 18,

				textAlign: "center",
			},
		},
		rowCell: {
			// 行头
			cell: {
				horizontalBorderColor: BORDER_COLOR,
				verticalBorderColor: BORDER_COLOR,
				backgroundColor: "#1b2035",
			},
			text: {
				fill: cellColor.value.rowCell,
				fontSize: 14,
				textAlign: "center",
			},
			measureText: {
				fill: cellColor.value.rowCell,
				fontSize: 14,
				textAlign: "center",
			},
			bolderText: {
				fill: cellColor.value.rowCell,
				fontSize: 14,
				textAlign: "center",
			},
		},
		colCell: {
			// 列头
			cell: {
				horizontalBorderColor: "#1b2035",
				verticalBorderColor: "#1b2035",
				backgroundColor: HEADER_BACK_COLOR,
			},
			text: {
				fill: cellColor.value.colCell,
				fontSize: 14,
				textAlign: "center",
			},
			measureText: {
				fill: cellColor.value.colCell,
				fontSize: 18,
				textAlign: "center",
			},
			bolderText: {
				fill: cellColor.value.colCell,
				fontSize: 18,
				textAlign: "center",
			},
		},
		dataCell: {
			// 数据
			icon: {
				size: 14,
				margin: {
					left: 10,
				},
			},
			cell: {
				horizontalBorderColor: BORDER_COLOR,
				verticalBorderColor: BORDER_COLOR,
				backgroundColorOpacity: 1,
				backgroundColor: "#1b2035",
				crossBackgroundColor: "#1b2035",
			},
			text: {
				fill: "#ffffff",
				fontSize: 14,
				textAlign: "center",
			},
			bolderText: {
				fill: "#ffffff",
				fontSize: 14,
				textAlign: "center",
			},
		},
		splitLine: {
			horizontalBorderColor: BORDER_COLOR,
			horizontalBorderColorOpacity: 1,
			horizontalBorderWidth: 2,
			verticalBorderColor: BORDER_COLOR,
			verticalBorderColorOpacity: 1,
			verticalBorderWidth: 2,
			showShadow: true,
			shadowWidth: 10,
			shadowColors: {
				left: "rgba(0,0,0,0.1)",
				right: "rgba(0,0,0,0)",
			},
		},
	};
	if (container.value) {
		if (
			!!s2DataConfig.fields && Object.keys(s2DataConfig.fields).some((key) => s2DataConfig.fields[key].length || aggregationId)
		) {
			if (!s2) {
				// 如果 s2 不存在，创建新实例
				s2 = new PivotSheet(container.value, s2DataConfig, s2Options);
			}
			// 更新数据和选项而不销毁 s2 实例
			s2.setDataCfg(s2DataConfig); // 更新数据
			s2.setOptions(s2Options); // 更新选项
			s2.setTheme(s2Theme); // 更新样式
			s2.on(S2Event.DATA_CELL_CLICK, (event) => {
				const cell = event.target.parent; // 获取目标单元格
				const cellData = cell.getMeta(); // 获取单元格的元数据
				let arr = [];
				if (cellData.data?.raw && Object.keys(cellData.data?.raw).length) {
					for (const key in cellData.data.raw) {
						arr.push({
							originalKey: key,
							originalValue: cellData.data.raw[key],
						});
					}
				}
				// 发送联动和下钻的目标数据
				emit("change-linkage", arr);
			});
			 
			await s2.render();
			// console.log(s2.facet.getRealHeight(), s2.facet.panelBBox.height);
			if(s2.facet?.getRealHeight() > s2.facet?.panelBBox.height) {
				canScroll.value = true
			} else {
				canScroll.value = false
			}
			const debounceRender = debounce(async (width, height) => {
				s2.changeSheetSize(width, height);
				await s2.render(false);
			}, 200);
			const resizeObserver = new ResizeObserver(([entry] = []) => {
				const [size] = entry.borderBoxSize || [];
				debounceRender(size.inlineSize, size.blockSize);
			});
			// 通过监听 container 来实现监听窗口大小变化
			resizeObserver.observe(container.value);
			// 别忘了表格销毁时取消监听
			s2.on(S2Event.LAYOUT_DESTROY, () => {
				resizeObserver.disconnect();
			});
			
			// s2.on(S2Event.GLOBAL_SCROLL, (event) => {
			// 	const { scrollY } = event;
			// 	const visibleHeight = s2.facet.getRealHeight() // 可视区域高度
			// 	const totalHeight = s2.facet.panelBBox.height;   // 总内容高度
			// 	// 判断是否到达底部
			// 	if (scrollY + totalHeight >= visibleHeight) {      // 允许10px的误差
			// 		if(timer1) clearTimeout(timer1)
			// 		timer1 = setTimeout(() => {
			// 			upNum = 0
			// 			downNum +=1
			// 			if(downNum >= 2) {
			// 				if(pageState.next) {
			// 					downNum = 0
			// 					emit("changePagi", 'next');
			// 				}
							
			// 			}
			// 		}, 1000)
			// 	}
			// 	if(scrollY === 0) {
			// 		if(timer2) clearTimeout(timer2)
			// 		timer2 = setTimeout(() => {
			// 			downNum = 0
			// 			upNum +=1
			// 			if(upNum >= 2) {
			// 				if(pageState.pre) {
			// 					upNum = 0
			// 					emit("changePagi", 'pre');
			// 				}
			// 			}
			// 		}, 1000)
			// 	}
			// })
		}
	}
};

function isHex(color) {
	// 判断css颜色是否是HEX
	const hexRegex = /^#([A-Fa-f0-9]{3}){1,2}$/;
	return hexRegex.test(color);
}
function rgbaToRgbHex(rgba) {
	// 将RGBA转换成HEX
	if (isHex(rgba)) {
		return rgba;
	}
	// 提取 rgba 或 rgb 值
	const parts = rgba
		.replace(/^rgba?\(|\s+|\)$/g, "") // 移除 'rgba(', 空格和 ')'
		.split(","); // 分割成数组
	// 将 R, G, B 转换为 HEX
	const r = parseInt(parts[0]).toString(16).padStart(2, "0");
	const g = parseInt(parts[1]).toString(16).padStart(2, "0");
	const b = parseInt(parts[2]).toString(16).padStart(2, "0");

	// 返回 RGB 转换后的 HEX 值（忽略 alpha）
	return `#${r}${g}${b}`;
}
watch(
	// 监听颜色变化重新渲染组件
	() => props.styles,
	async (val) => {
		const { colCell, rowCell } = val;
		cellColor.value.colCell = rgbaToRgbHex(colCell);
		cellColor.value.rowCell = rgbaToRgbHex(rowCell);
		initTwoDimenTable();
	},
	{
		deep: true,
	}
);
watch(
	newValue,
	(n) => {
		console.log('n11111', n);
		
		if(time) clearTimeout(time)
		time = setTimeout(() => {
			aggregationId = n.dataSetting.aggregation.id || '' 
			pageState.next =
				typeof n.value?.next === "boolean" ? n.value.next : pageState.next;
			pageState.pre =
				typeof n.value?.previous === "boolean" ? n.value.previous : pageState.pre;
			s2DataConfig.fields = n.value?.fields;
			s2DataConfig.meta = n.value?.meta;
			s2DataConfig.data = n.value?.data;
			total.value = n.value?.total ? Number(n.value?.total) : 0;
			s2Options.hierarchyType = n.dataSetting.hierarchyType;

			const { colCell, rowCell } = n.styles;
			if (colCell && rowCell) {
				cellColor.value.colCell = rgbaToRgbHex(colCell);
				cellColor.value.rowCell = rgbaToRgbHex(rowCell);
			}
			initTwoDimenTable();
		}, 500);
	},
	{
		immediate: true,
		deep: true,
	}
);
</script>
<style lang="scss" scoped>
.twoContainer {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: flex-end;
	position: relative;
	.pagi {
		display: flex;
		align-items: center;
		color: #ffffff;
		gap: 10px;
		height: 10%;
		// position: absolute;
		// bottom: 5px;
		// right: 5px;
		// &:hover {
		// 	opacity: 0.2;
		// }
	}
}
/* 自定义分页下拉框样式 */
.ant-pagination{
	.ant-select-dropdown {
	  left: 0px !important;
	  top: -145px !important
	}
}
</style>
